package cn.time1024.time_app.ui.dashboard

import android.os.Bundle
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.time1024.time_app.databinding.FragmentDashboardBinding
import androidx.navigation.fragment.findNavController
import com.example.timeassistant.network.ApiService
import com.example.timeassistant.network.ResponseEnvelope
import com.example.timeassistant.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class DashboardFragment : Fragment() {

    private var _binding: FragmentDashboardBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentDashboardBinding.inflate(inflater, container, false)
        val root: View = binding.root
        setupList()
        setupAddButton()
        setupSwipeRefresh()
        loadPage(reset = true)
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    // ====== 列表与分页逻辑 ======
    private lateinit var adapter: TasksAdapter
    private var pageNo = 1
    private var pageSize = 9
    private var isLoading = false
    private var hasMore = true
    private var searchText: String = ""
    private var completed: Boolean? = false
    private var sortField: String? = "createTime"
    private var sortOrder: String? = "desc"
    private var priorityFilter: String? = null

    private fun setupList() {
        adapter = TasksAdapter(
            onToggleComplete = { item, isChecked ->
                RetrofitClient.api.updateTaskStatus(ApiService.TaskSubmit(taskId = item.taskId, completed = isChecked))
                    .enqueue(simpleVoidCallback(if (isChecked) "任务已完成" else "任务已取消完成", "更新失败"))
            },
            onEdit = { item ->
                val bundle = android.os.Bundle().apply {
                    putLong("taskId", item.taskId ?: 0L)
                    putString("title", item.title)
                    putString("description", item.description)
                    putString("dueDate", item.dueDate)
                    putString("priority", item.priority)
                }
                findNavController().navigate(cn.time1024.time_app.R.id.navigation_task_detail, bundle)
            },
            onDelete = { item ->
                RetrofitClient.api.deleteTask(ApiService.TaskSubmit(taskId = item.taskId))
                    .enqueue(simpleVoidCallback("删除成功", "删除失败"))
            },
            onTogglePinned = { item ->
                val pinned = if (item.pinned == "Y") "N" else "Y"
                RetrofitClient.api.updateTaskPinned(ApiService.TaskSubmit(taskId = item.taskId, pinned = pinned))
                    .enqueue(simpleVoidCallback("置顶状态已更新", "更新失败"))
            }
        )
        val rv = binding.rvTasks
        rv.layoutManager = LinearLayoutManager(requireContext())
        rv.adapter = adapter
        rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dy <= 0) return
                val lm = recyclerView.layoutManager as LinearLayoutManager
                val lastVisible = lm.findLastVisibleItemPosition()
                if (!isLoading && hasMore && lastVisible >= adapter.itemCount - 2) {
                    loadPage(reset = false)
                }
            }
        })
    }

    private fun setupSwipeRefresh() {
        binding.swipeRefresh.setOnRefreshListener {
            loadPage(reset = true)
        }
        binding.btnFilter.setOnClickListener {
            showFilterDialog()
        }
        binding.emptyStateAddButton.setOnClickListener {
            val bundle = android.os.Bundle()
            findNavController().navigate(cn.time1024.time_app.R.id.navigation_task_detail, bundle)
        }
        binding.btnHeaderAdd.setOnClickListener {
            val bundle = android.os.Bundle()
            findNavController().navigate(cn.time1024.time_app.R.id.navigation_task_detail, bundle)
        }
    }

    private fun loadPage(reset: Boolean) {
        if (isLoading) return
        isLoading = true
        if (reset) {
            pageNo = 1
            hasMore = true
        }
        val call = RetrofitClient.api.getTasksPage(
            searchText = if (searchText.isBlank()) null else searchText,
            pageNo = pageNo,
            pageSize = pageSize,
            sortField = sortField,
            sortOrder = sortOrder,
            completed = completed,
            priority = priorityFilter
        )
        call.enqueue(object : Callback<ResponseEnvelope<ApiService.PageResult<ApiService.TaskItem>>> {
            override fun onResponse(
                call: Call<ResponseEnvelope<ApiService.PageResult<ApiService.TaskItem>>>,
                response: Response<ResponseEnvelope<ApiService.PageResult<ApiService.TaskItem>>>
            ) {
                isLoading = false
                binding.swipeRefresh.isRefreshing = false
                if (!response.isSuccessful) {
                    Toast.makeText(requireContext(), "加载失败：${response.code()}", Toast.LENGTH_SHORT).show()
                    return
                }
                val body = response.body()
                val data = body?.data
                val list = data?.rows ?: emptyList()
                val total = data?.totalRows ?: 0
                binding.tvTotal.text = "共 ${total} 条数据"
                if (reset) {
                    adapter.replaceAll(list)
                } else {
                    adapter.appendAll(list)
                }
                val loaded = adapter.itemCount
                hasMore = loaded < total
                if (hasMore) pageNo += 1
                binding.emptyStateContainer.visibility = if (adapter.itemCount == 0) View.VISIBLE else View.GONE
                binding.rvTasks.visibility = if (adapter.itemCount == 0) View.GONE else View.VISIBLE
            }

            override fun onFailure(
                call: Call<ResponseEnvelope<ApiService.PageResult<ApiService.TaskItem>>>,
                t: Throwable
            ) {
                isLoading = false
                binding.swipeRefresh.isRefreshing = false
                Toast.makeText(requireContext(), "网络错误：${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    // ====== 新增与编辑、删除交互 ======
    private fun setupAddButton() {
        binding.fabAddTask.setOnClickListener {
            val bundle = android.os.Bundle()
            findNavController().navigate(cn.time1024.time_app.R.id.navigation_task_detail, bundle)
        }
    }

    private fun showFilterDialog() {
        val sortFields = arrayOf("创建时间", "截止时间", "优先级")
        val sortFieldCodes = arrayOf("createTime", "dueDate", "priority")
        val sortOrders = arrayOf("升序", "降序")
        val sortOrderCodes = arrayOf("asc", "desc")
        val priorities = arrayOf("全部", "高", "中", "低")
        val priorityCodes = arrayOf(null, "high", "medium", "low")
        val statuses = arrayOf("全部", "未完成", "已完成")

        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 16, 32, 0)
        }
        val spSortField = android.widget.Spinner(requireContext()).apply {
            adapter = android.widget.ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, sortFields)
            setSelection(sortFieldCodes.indexOf(sortField ?: "createTime"))
        }
        val spSortOrder = android.widget.Spinner(requireContext()).apply {
            adapter = android.widget.ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, sortOrders)
            setSelection(if ((sortOrder ?: "desc") == "asc") 0 else 1)
        }
        val spPriority = android.widget.Spinner(requireContext()).apply {
            adapter = android.widget.ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, priorities)
            val idx = priorityCodes.indexOf(priorityFilter)
            setSelection(if (idx >= 0) idx else 0)
        }
        val spStatus = android.widget.Spinner(requireContext()).apply {
            adapter = android.widget.ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, statuses)
            val idx = when (completed) { null -> 0; false -> 1; true -> 2 }
            setSelection(idx)
        }
        val lp = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val tv1 = android.widget.TextView(requireContext()).apply { text = "排序字段" }
        val tv2 = android.widget.TextView(requireContext()).apply { text = "排序方式" }
        val tv3 = android.widget.TextView(requireContext()).apply { text = "优先级" }
        val tv4 = android.widget.TextView(requireContext()).apply { text = "状态" }
        wrapper.addView(tv1, lp); wrapper.addView(spSortField, lp)
        wrapper.addView(tv2, lp); wrapper.addView(spSortOrder, lp)
        wrapper.addView(tv3, lp); wrapper.addView(spPriority, lp)
        wrapper.addView(tv4, lp); wrapper.addView(spStatus, lp)

        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("筛选与排序")
            .setView(wrapper)
            .setPositiveButton("应用") { _, _ ->
                sortField = sortFieldCodes[spSortField.selectedItemPosition]
                sortOrder = sortOrderCodes[spSortOrder.selectedItemPosition]
                priorityFilter = priorityCodes[spPriority.selectedItemPosition]
                completed = when (spStatus.selectedItemPosition) { 0 -> null; 1 -> false; 2 -> true; else -> null }
                loadPage(reset = true)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showAddDialog() {
        val etTitle = EditText(requireContext()).apply { hint = "标题" }
        val etDesc = EditText(requireContext()).apply { hint = "描述" }
        // 默认截止时间：当前时间起10天后
        var selectedDue: String? = run {
            val cal = java.util.Calendar.getInstance()
            cal.add(java.util.Calendar.DAY_OF_MONTH, 10)
            val fmt = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
            fmt.format(cal.time)
        }
        val tvDuePreview = android.widget.TextView(requireContext()).apply { text = "截止时间: ${selectedDue}" }
        val btnPickDue = android.widget.Button(requireContext()).apply { text = "选择截止时间" }
        val spPriority = android.widget.Spinner(requireContext())
        // 优先级显示为中文：高/中/低，提交时映射为 high/medium/low
        val displayPriorities = arrayOf("高", "中", "低")
        val priorityCodes = arrayOf("high", "medium", "low")
        spPriority.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, displayPriorities)

        btnPickDue.setOnClickListener {
            val cal = java.util.Calendar.getInstance()
            DatePickerDialog(requireContext(), { _, y, m, d ->
                TimePickerDialog(requireContext(), { _, h, min ->
                    val fmt = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
                    cal.set(y, m, d, h, min)
                    selectedDue = fmt.format(cal.time)
                    tvDuePreview.text = "截止时间: ${selectedDue}"
                }, cal.get(java.util.Calendar.HOUR_OF_DAY), cal.get(java.util.Calendar.MINUTE), true).show()
            }, cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH), cal.get(java.util.Calendar.DAY_OF_MONTH)).show()
        }

        val container = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 16, 32, 0)
            addView(etTitle, container)
            addView(etDesc, container)
            addView(tvDuePreview, container)
            addView(btnPickDue, container)
            addView(spPriority, container)
        }

        AlertDialog.Builder(requireContext())
            .setTitle("新增任务")
            .setView(wrapper)
            .setPositiveButton("确定") { _, _ ->
                val title = etTitle.text?.toString()?.trim().orEmpty()
                val desc = etDesc.text?.toString()?.trim().orEmpty()
                if (title.isEmpty()) {
                    Toast.makeText(requireContext(), "标题不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                val payload = ApiService.TaskSubmit(
                    title = title,
                    description = desc,
                    dueDate = selectedDue,
                    priority = priorityCodes[spPriority.selectedItemPosition]
                )
                RetrofitClient.api.addTask(payload).enqueue(simpleVoidCallback("添加成功", "添加失败"))
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showItemMenu(item: ApiService.TaskItem) { /* 保留但不再使用，功能由行内按钮承载 */ }

    private fun showEditDialog(item: ApiService.TaskItem) {
        val etTitle = EditText(requireContext()).apply { hint = "标题"; setText(item.title ?: "") }
        val etDesc = EditText(requireContext()).apply { hint = "描述"; setText(item.description ?: "") }
        val tvDuePreview = android.widget.TextView(requireContext()).apply { text = "截止时间: ${item.dueDate ?: "未选择"}" }
        val btnPickDue = android.widget.Button(requireContext()).apply { text = "选择截止时间" }
        val spPriority = android.widget.Spinner(requireContext())
        val displayPriorities = arrayOf("高", "中", "低")
        val priorityCodes = arrayOf("high", "medium", "low")
        spPriority.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, displayPriorities)
        spPriority.setSelection(priorityCodes.indexOf(item.priority ?: "medium"))

        var selectedDue: String? = item.dueDate
        btnPickDue.setOnClickListener {
            val cal = java.util.Calendar.getInstance()
            DatePickerDialog(requireContext(), { _, y, m, d ->
                TimePickerDialog(requireContext(), { _, h, min ->
                    val fmt = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
                    cal.set(y, m, d, h, min)
                    selectedDue = fmt.format(cal.time)
                    tvDuePreview.text = "截止时间: ${selectedDue}"
                }, cal.get(java.util.Calendar.HOUR_OF_DAY), cal.get(java.util.Calendar.MINUTE), true).show()
            }, cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH), cal.get(java.util.Calendar.DAY_OF_MONTH)).show()
        }
        val container = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 16, 32, 0)
            addView(etTitle, container)
            addView(etDesc, container)
            addView(tvDuePreview, container)
            addView(btnPickDue, container)
            addView(spPriority, container)
        }
        AlertDialog.Builder(requireContext())
            .setTitle("编辑任务")
            .setView(wrapper)
            .setPositiveButton("保存") { _, _ ->
                val title = etTitle.text?.toString()?.trim().orEmpty()
                val desc = etDesc.text?.toString()?.trim().orEmpty()
                if (title.isEmpty()) {
                    Toast.makeText(requireContext(), "标题不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                val payload = ApiService.TaskSubmit(
                    taskId = item.taskId,
                    title = title,
                    description = desc,
                    dueDate = selectedDue,
                    priority = priorityCodes[spPriority.selectedItemPosition],
                    completed = item.status == "已完成",
                    pinned = item.pinned
                )
                RetrofitClient.api.editTask(payload).enqueue(simpleVoidCallback("保存成功", "保存失败"))
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun nowPlusOneDay(): String {
        val cal = java.util.Calendar.getInstance()
        cal.add(java.util.Calendar.DAY_OF_MONTH, 1)
        val fmt = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", java.util.Locale.getDefault())
        return fmt.format(cal.time)
    }

    private fun simpleVoidCallback(successMsg: String, failMsg: String): Callback<ResponseEnvelope<Any?>> {
        binding.swipeRefresh.isRefreshing = true
        return object : Callback<ResponseEnvelope<Any?>> {
            override fun onResponse(call: Call<ResponseEnvelope<Any?>>, response: Response<ResponseEnvelope<Any?>>) {
                binding.swipeRefresh.isRefreshing = false
                val body = response.body()
                val ok = (body?.success == true) || (body?.code == "00000")
                if (response.isSuccessful && ok) {
                    Toast.makeText(requireContext(), successMsg, Toast.LENGTH_SHORT).show()
                    loadPage(reset = true)
                } else {
                    Toast.makeText(requireContext(), body?.message ?: failMsg, Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<ResponseEnvelope<Any?>>, t: Throwable) {
                binding.swipeRefresh.isRefreshing = false
                Toast.makeText(requireContext(), "$failMsg：${t.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 顶部导航栏按钮已在 setupSwipeRefresh 中绑定，无需额外处理
    }
}
